<!-- 系统管理-应用管理 -->
<script setup lang="tsx">
import {
  Box,
  Delete,
  Edit,
  Plus,
  Warning,
} from '@element-plus/icons-vue'
import type {
  Action,
} from 'element-plus'
import {
  ElButton,
  ElDivider,
  ElSwitch,
  ElTooltip,
  ElTree,
} from 'element-plus'
import { FormModal } from './components'
import { defaultForm } from './index'
import type {
  ApplicationInfo,
  ApplicationSaveOrUpdateParams,
  MenuInfo,
  TableColumn,
} from '@/types'
import {
  sysApplicationApi,
  sysApplicationMenuApi,
} from '@/api'

// ------------------use------------------
// #region
const { withLoading, loading, vLoading }
  = useDefineLoading()
const [tableData, setTableData] = useState<
  ApplicationInfo[]
>([])
const [roleForm, setRoleForm] = useState<
  Partial<ApplicationSaveOrUpdateParams>
>({
  ...defaultForm,
})
const [menuData, setMenuData] = useState<MenuInfo[]>([])
const [formModalTitle, setFormModalTitle]
  = useState<string>('')
const { $message, $confirm } = useCurrentInstance()
const [isAssignmentsMenu, setIsAssignmentsMenu]
  = useState<boolean>(false)
const [selectApply, setSelectApply]
  = useQuoteState<ApplicationInfo>({} as any)
// #endregion
// ------------------静态变量------------------
// #region
const columns: TableColumn<ApplicationInfo>[] = [
  {
    key: uuid(),
    type: 'index',
    label: '#',
  },
  {
    key: uuid(),
    prop: 'applicationName',
    label: '应用名称',
  },
  {
    key: uuid(),
    label: '启用',
    header: () => {
      return (
        <span class="align-center flex justify-center">
          启用
          <el-tooltip
            content="页面不会注册"
            placement="top"
          >
            <el-icon class="c-pointer margin-left-xs text-orange">
              <Warning />
            </el-icon>
          </el-tooltip>
        </span>
      )
    },
    render({ row }) {
      return h(ElSwitch, {
        modelValue: row.applicationEnable,
        activeValue: 1,
        inactiveValue: 0,
        onclick: () => {
          handlerSwitchStatus(row, 'applicationEnable')
        },
      })
    },
  },
  {
    key: uuid(),
    fixed: 'right',
    label: '操作',
    width: '150',
    render({ row }) {
      return (
        <>
          <ElTooltip content="编辑" placement="top">
            <ElButton
              link
              type="primary"
              icon={Edit}
              onclick={() => showEditDialog(row)}
            >
            </ElButton>
          </ElTooltip>
          <ElDivider direction="vertical" />
          <ElTooltip content="分配菜单" placement="top">
            <ElButton
              link
              type="warning"
              icon={Box}
              onclick={() => showAssignmentsMenuDialog(row)}
            >
            </ElButton>
          </ElTooltip>
          <ElDivider direction="vertical" />
          <ElTooltip content="删除" placement="top">
            <ElButton
              link
              type="danger"
              icon={Delete}
              onclick={() => deleteData(row.id)}
            >
            </ElButton>
          </ElTooltip>
        </>
      )
    },
  },
]
// #endregion
// ------------------动态变量------------------
// #region

// #endregion
// ------------------ref-----------
// #region
const modalRef = ref<InstanceType<typeof FormModal>>()
const treeRef = ref<InstanceType<typeof ElTree>>()
// #endregion
// ------------------reactive------
// #region

// #endregion
// ------------------computed------
// #region

// #endregion
// ------------------生命周期------------------
// #region
onMounted(() => {
  getTableData()
  getMenuData()
})
// #endregion
// ------------------内置方法---------------------
// #region

// #endregion
// ------------------方法---------------------
// #region

async function getTableData() {
  const { data: res } = await withLoading(
    sysApplicationApi.queryList,
  )()
  setTableData(res)
}
async function getMenuData() {
  const { data: res } = await sysMenuApi.queryTreeList()
  setMenuData(res)
}
async function getApplyBindMenu(id: number) {
  const { data } = await withLoading(
    sysApplicationMenuApi.queryBindMenuId,
    'tree',
  )(id)
  treeRef.value?.setCheckedKeys(data)
}
/** 删除数据 */
async function deleteData(id: number) {
  const res: Action = await $confirm(
    '该操作将永久删除该角色，确定删除？',
    '警告',
    {
      type: 'warning',
    },
  ).catch(e => e)

  if (res !== 'confirm')
    return
  const { code } = await sysApplicationApi.deleteById(id)
  if (code !== 200)
    return
  getTableData()
}
async function saveOrUpdate(params: Partial<ApplicationSaveOrUpdateParams>) {
  removeUnnecessaryParams(params)
  const { code } = await sysApplicationApi.saveOrUpdate(
    params,
  )
  if (code !== 200)
    return
  getTableData()
  modalRef.value?.close()
  $message.success('保存成功！')
}
async function assignmentsMenu() {
  const keys = treeRef.value?.getCheckedKeys()
  if (!keys || keys?.length === 0)
    return
  const n = keys.map(key => ({
    menuId: key as number,
    applicationId: selectApply.id,
    enable: selectApply.applicationEnable,
  }))
  const { code } = await sysApplicationMenuApi.batchMenuId(
    n,
  )
  if (code !== 200)
    return
  setIsAssignmentsMenu(false)
  $message.success('菜单分配成功！')
}
async function showAddDialog() {
  setFormModalTitle('新增')
  setRoleForm({
    ...defaultForm,
  })
  await nextTick()
  modalRef.value?.open()
}
async function showEditDialog(row: ApplicationInfo) {
  setFormModalTitle('编辑')
  setRoleForm({
    ...defaultForm,
    ...row,
  })
  await nextTick()
  modalRef.value?.open()
}
async function showAssignmentsMenuDialog(row: ApplicationInfo) {
  setSelectApply(row)
  setIsAssignmentsMenu(true)
  await nextTick()
  getApplyBindMenu(row.id)
}
function handlerSwitchStatus(row: Partial<ApplicationInfo>, str: string) {
  const params: Partial<ApplicationSaveOrUpdateParams> = {
    id: row.id,
    [str]: +!(row as any)[str],
  }
  saveOrUpdate(params)
}
// #endregion
</script>

<template>
  <div
    class="padding-sm flex-direction flex align-end container"
  >
    <view-table
      :loading="loading"
      :columns="columns"
      :data="tableData"
    >
      <template #actions>
        <ElButton
          plain
          type="success"
          :icon="Plus"
          @click="showAddDialog"
        >
          新增
        </ElButton>
      </template>
    </view-table>

    <FormModal
      ref="modalRef"
      :title="formModalTitle"
      :data="roleForm"
      @save-success="saveOrUpdate(roleForm)"
    />
    <!-- 分配菜单 -->
    <el-dialog
      v-model="isAssignmentsMenu"
      width="600"
      append-to-body
      title="分配菜单"
    >
      <b-scrollbar
        class="padding-0"
        style="max-height: 50vh"
      >
        <ElTree
          ref="treeRef"
          v-loading="{
            space: 'tree',
          }"
          check-strictly
          accordion
          :props="{
            label: 'menuName',
          }"
          node-key="id"
          :data="menuData"
          show-checkbox
        />
      </b-scrollbar>
      <template #footer>
        <ElButton @click="setIsAssignmentsMenu(false)">
          取 消
        </ElButton>
        <ElButton type="primary" @click="assignmentsMenu">
          确 定
        </ElButton>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
//------------------组件样式------------------
//-------------样式穿透-------------
</style>
